package com.kaifamiao.mybatis.basics.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;

public class LocalDateTypeHandler extends BaseTypeHandler<LocalDate> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, LocalDate date, JdbcType type) throws SQLException {
        System.out.println( "为第" + index + "个参数占位符设置参数: " + date );
        // 将 LocalDate 转换为 java.sql.Date
        java.sql.Date birthdate = date != null ? java.sql.Date.valueOf( date ) : null ;
        // 通过 PreparedStatement 为 第 index 个占位符设置参数值
        ps.setDate( index, birthdate );
    }

    @Override
    public LocalDate getNullableResult(ResultSet rs, String label) throws SQLException {
        System.out.println( "根据列名或别名获取" + label + "列的值" );
        // 从结果集的当前行中获取 label 对应的列的值
        java.sql.Date date = rs.getDate( label );
        // 将 java.sql.Date实例 转换为 java.time.LocalDate 实例
        LocalDate birthdate = date != null ? date.toLocalDate() : null;
        return birthdate;
    }

    @Override
    public LocalDate getNullableResult(ResultSet rs, int index) throws SQLException {
        System.out.println( "根据列索引获取" + index + "列的值" );
        // 从结果集的当前行中获取 index 对应的列的值
        java.sql.Date date = rs.getDate( index );
        // 将 java.sql.Date实例 转换为 java.time.LocalDate 实例
        LocalDate birthdate = date != null ? date.toLocalDate() : null;
        return birthdate;
    }

    @Override
    public LocalDate getNullableResult(CallableStatement cs, int index) throws SQLException {
        System.out.println( "根据传出参数的索引获取" + index + "处的传出参数" );
        // 从CallableStatement中获取 index 处的传出参数值
        java.sql.Date date = cs.getDate( index );
        // 将 java.sql.Date实例 转换为 java.time.LocalDate 实例
        LocalDate birthdate = date != null ? date.toLocalDate() : null;
        return birthdate;
    }

}
